package com.blog.controller.user;

import com.blog.entity.Image;
import com.blog.entity.User;
import com.blog.service.PictureService;
import com.blog.util.FileCopyUtil;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Api(tags = "用户图片上传到静态目录以供使用")
@Slf4j
@RestController
@RequestMapping("/user")
public class ImageUploadController {

	@Autowired
	private PictureService pictureService;

	@GetMapping("/images")
	public ModelAndView imageList(ModelAndView modelAndView, HttpSession session,
                                  @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        User user = (User)session.getAttribute("user");
	    PageHelper.startPage(pageNum,8);
		List<Image> imageList = pictureService.selectPictureList(user.getId());
		modelAndView.addObject("imageList", imageList);
		modelAndView.setViewName("user/images.html");
		return modelAndView;
	}

    @ApiOperation("跳转图片上传页面")
    @GetMapping("/images/input")
    public ModelAndView input(ModelAndView modelAndView){
        modelAndView.addObject("image", new Image());
        modelAndView.setViewName("user/images-input.html");
        return modelAndView;
    }

	@ApiOperation("上传图片")
	@PostMapping("/imageUpload")
	public ModelAndView imageUpload(ModelAndView modelAndView,@RequestParam("file") MultipartFile file,
									HttpSession session,
									HttpServletRequest request, HttpServletResponse response) {
		Image image = new Image();
        User user = (User)session.getAttribute("user");
        image.setUserId(user.getId());

		try {
			request.setCharacterEncoding("utf-8");
			response.setHeader("Content-Type", "application/json");

			File targetFile = null;
			String url = "";
			String fileName = file.getOriginalFilename();

			if (StringUtils.isNotBlank(fileName)) {
				/**
				 * 图片访问的URI-不带端口号
				 * request.getScheme()：协议http/https
				 * request.getServerName()：IP-服务器名
				 * request.getServerPort()：端口
				 * request.getContextPath()：当前页面所在应用的名字
				 */
				String returnUrl = request.getScheme() + "://" + request.getServerName() + ":"+ request.getServerPort() + request.getContextPath() + "/upload/images/";
				//文件临时存储位置
				String path = request.getSession().getServletContext().getRealPath("") + "upload" + File.separator + "images";
				//文件后缀
				String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
				//新的文件名
				fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + fileSuffix;

				//设置日期文件夹
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String fileAdd = sdf.format(new Date());
				//获取文件夹路径
				path = path + File.separator + fileAdd + File.separator;
				File file1 = new File(path);

				//如果文件夹不存在则创建
				if (!file1.exists() && !file1.isDirectory()) {
					if (!file1.mkdirs()) {
						throw new IOException("文件夹创建失败,路径为：" + file1);
					}
				}
				//将图片存入文件夹
				targetFile = new File(file1, fileName);

				//将上传的文件写到服务器上指定的文件。
				file.transferTo(targetFile);
				String projectPath = System.getProperty("user.dir");
				//文件复制
				String src = path + fileName;
				//根据自己系统的resource 目录所在位置进行自行配置
				String destDir = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "static" + File.separator + "upload" + File.separator + "images" + File.separator + fileAdd + File.separator;
				FileCopyUtil.copyFile(src, destDir, fileName);

				url = returnUrl + fileAdd + "/" + fileName;

				//默认图片可用
				image.setValid(true);
				image.setUrl(url);
				image.setCreateTime(new Date());
				pictureService.insertPicture(image);

			}
		} catch (Exception e) {
			modelAndView.addObject("message","图片上传失败");
			log.info("图片上传失败: "+e.getMessage());
		}

		modelAndView.addObject("image",image);
        modelAndView.setViewName("user/images-input.html");
		return modelAndView;
	}

	@ApiOperation("删除图片")
	@GetMapping("/imageDelete/{id}")
	public ModelAndView imageDelete(@PathVariable Long id, RedirectAttributes attributes,
                                    HttpSession session,
									ModelAndView modelAndView, HttpServletRequest request){

        User user = (User)session.getAttribute("user");
//		//先查找图片链接
//		String url = pictureService.selectURLById(id,user.getId());

		//根据id删除数据库图片信息- 设置为不可用
		int dResult = pictureService.updateImageValid(id,user.getId());

		if(dResult == 1){
			attributes.addFlashAttribute("message","图片删除成功");
		}else {
			attributes.addFlashAttribute("message","图片删除失败");
		}
//		//图片绝对路径
//		String path = imagePath(url,request);
//		File file = new File(path);
//		//删除由此抽象路径名表示的文件或目录
//		boolean flagDelete = file.delete();
//		if(flagDelete && dResult >= 1){
//			attributes.addFlashAttribute("message","图片彻底删除成功");
//		}else if(flagDelete){
//			attributes.addFlashAttribute("message","本地图片删除成功");
//		}else if(dResult >= 1){
//			attributes.addFlashAttribute("message","DB图片信息删除成功");
//		}else{
//			attributes.addFlashAttribute("message","图片删除失败");
//		}
		modelAndView.setViewName("redirect:/user/images");
		return modelAndView;
	}

	/**
	 * 图片地址转化
	 * http://suoyue.top:80/upload/images/yyyyMMdd/xxoo.png -> /Users/test/IdeaProjects/blog/src/main/resources/static/upload/images/yyyyMMdd/xxoo.png
	 */
	public String imagePath(String imageURL,HttpServletRequest request){
		//http://suoyue.top:80/upload/images/yyyyMMdd/xxoo.png
		String returnUrl = request.getScheme() + "://" + request.getServerName() + ":"+ request.getServerPort() + request.getContextPath();
		//	/upload/images/yyyyMMdd/xxoo.png
		String imagePath = imageURL.substring(returnUrl.length(),imageURL.length());
		String projectPath = System.getProperty("user.dir");
		//图片绝对路径
		String path = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "static" + imagePath;
		return path;
	}


}
